package com.ruoyi.biz.service;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.biz.domain.BizProject;
import com.ruoyi.biz.mapper.BizProjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;

import java.util.Arrays;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.biz.mapper.BizTrusteeMapper;
import com.ruoyi.biz.domain.BizTrustee;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;


/**
 * 受托方管理Service业务层处理
 *
 * @author tianl
 * @date 2024-12-29
 */
@Service
public class BizTrusteeService extends ServiceImpl<BizTrusteeMapper, BizTrustee> {
    @Autowired
    private BizProjectMapper bizProjectMapper;

    /**
     * 分页查询受托方管理
     */
    public IPage<BizTrustee> listPage(BizTrustee req) {
        return baseMapper.list(PageUtils.page(), req);
    }

    /**
     * 查询受托方管理列表
     */
    public List<BizTrustee> list(BizTrustee req) {
        return baseMapper.list(req);
    }

    /**
     * 根据ID查询
     */
    public BizTrustee selectById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 新增修改受托方管理
     */
    @Transactional(rollbackFor = Exception.class)
    public void beforeSave(BizTrustee bizTrustee) {
        if (bizTrustee.getId() != null) {
            bizTrustee.setUpdateTime(DateUtils.getNowDate());
        } else {
            bizTrustee.setCreateTime(DateUtils.getNowDate());
            bizTrustee.setUpdateTime(DateUtils.getNowDate());
            bizTrustee.setUserId(getUserId());
        }
        saveOrUpdate(bizTrustee);
    }

    /**
     * 批量删除受托方管理
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Long[] ids) {
        for (Long id : ids) {
            LambdaQueryWrapper<BizProject> wrapper = new LambdaQueryWrapper<>();
            wrapper.and(i -> i.eq(BizProject::getTrusteeId, id));
            List<BizProject> projectList = bizProjectMapper.selectList(wrapper);
            if (!CollectionUtils.isEmpty(projectList)) {
                BizTrustee model = selectById(id);
                List<String> pName = projectList.stream().map(BizProject::getProjectName).collect(Collectors.toList());
                throw new ServiceException(model.getCompanyName() + "被项目[" + String.join(",", pName) + "]使用，不允许删除！");
            }
        }
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

}
